package com.sixteen.theGreat.settings.service.impl;

import com.sixteen.theGreat.commons.constants.Constants;
import com.sixteen.theGreat.commons.entity.ReturnObject;
import com.sixteen.theGreat.settings.entity.User;
import com.sixteen.theGreat.settings.mapper.UserMapper;
import com.sixteen.theGreat.settings.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户
     * @param userName 用户输入的用户名
     * @param password 用户输入的密码
     * @return 将结果信息封装到一个实体类中,返回该实体类
     */
    @Override
    public Object queryUser(String userName, String password, HttpServletRequest request) {
        User user=userMapper.selectUser(userName,password);
        ReturnObject returnObject=new ReturnObject();
        if (user == null){
            returnObject.setCode(0);
            returnObject.setMessage("用户名或密码错误");
        }else {
            returnObject.setCode(1);
            request.getSession().setAttribute(Constants.SESSION_USER,user);
        }
        return returnObject;
    }

    /**
     * 注册新用户
     * @param user 新用户注册的详细信息包装到的实体类
     * @return 影响的行数
     */
    @Override
    public Object addUser(User user, HttpServletRequest request) {
        int reg = userMapper.insertUser(user);
        ReturnObject returnObject=new ReturnObject();
        if (reg > 0){
            returnObject.setCode(1);
//            注册session
            request.getSession().setAttribute(Constants.SESSION_USER,user);
        }else {
            returnObject.setCode(0);
            returnObject.setMessage("用户名或密码错误");
        }
        return returnObject;
    }
}
